Following libraries will be used

library(GA)
source('./my_ga.R')

Set random seed for reproducible experiments.

set.seed(1)

Genetic Alghoritm use to solve optimization problem

Function optimization with few local optimums

\[ \begin{array}{c} (x^2 + x) * \cos(x) \end{array} \]

GA work animation

GA <- my_ga(fitness, min = min, max = max, monitor = monitor, seed = 1);

GA results summary

## +-----------------------------------+
## |         Genetic Algorithm         |
## +-----------------------------------+
## 
## GA settings: 
## Type                  =  real-valued 
## Population size       =  50 
## Number of generations =  100 
## Elitism               =  2 
## Crossover probability =  0.8 
## Mutation probability  =  0.1 
## Search domain 
##      x1
## Min -10
## Max  10
## 
## GA results: 
## Iterations             = 100 
## Fitness function value = 100.2238 
## Solution               = 
##          [,1]
## [1,] 9.620346

Comparing with other alghoritms

Rastrigin function optimization

\[ \begin{array}{c} 10N+\sum\limits_{n=1}^N [x^2_n - 10 \cos(2\pi x_n)] \end{array} \]

GA work animation

monitor <- function(obj) {
  contour(x1, x2, f, drawlabels = FALSE, col = gray(0.5))
  title(paste("iteration =", obj@iter), font.main = 1)
  points(obj@population, pch = 20, col = 2)
  #Sys.sleep(0.2)
}
GA <- my_ga(type = "real-valued",
  fitness = function(x) -Rastrigin(x[1], x[2]),
  min = c(-5.12, -5.12), max = c(5.12, 5.12), popSize = 50,
  maxiter = 100, monitor = monitor, seed = 1)

Summary

## +-----------------------------------+
## |         Genetic Algorithm         |
## +-----------------------------------+
## 
## GA settings: 
## Type                  =  real-valued 
## Population size       =  50 
## Number of generations =  100 
## Elitism               =  2 
## Crossover probability =  0.8 
## Mutation probability  =  0.1 
## Search domain 
##        x1    x2
## Min -5.12 -5.12
## Max  5.12  5.12
## 
## GA results: 
## Iterations             = 100 
## Fitness function value = -7.148418e-07 
## Solution               = 
##               [,1]         [,2]
## [1,] -3.238748e-05 5.053937e-05

Solution after optimization with Newton-type algorithm

NLM <- nlm(function(x) Rastrigin(x[1], x[2]), GA@solution)
NLM[c("minimum", "estimate")]
## $minimum
## [1] 0
## 
## $estimate
## [1] -3.251085e-14  4.773029e-15

Optimization of Noisy Functions

\[ \begin{array}{c} [\sum\limits_{n=1}^N nx^4_n] + N_n(0,1) \end{array} \]

monitor <- function(obj) {
  contour(x1, x2, f, drawlabels = FALSE, col = gray(0.5))
  title(paste("iteration =", obj@iter), font.main = 1)
  points(obj@population, pch = 20, col = 2)
  #Sys.sleep(0.1)
}
GA <- my_ga(type = "real-valued",
         fitness = function(x) -Noisy(x[1], x[2]),
         min = c(-5.12, -5.12), max = c(5.12, 5.12), popSize = 50,
         maxiter = 100, monitor = monitor, seed = 1)